package com.example.test.advice.第九章_多线程和并发.建议130_使用CountDownLatch协调子线程;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;

public class Client {

    public static void main(String[] args) throws Exception{
        //参加赛跑认识
        int num = 10;
        //发令枪只响一次
        CountDownLatch begin = new CountDownLatch(1);
        CountDownLatch end = new CountDownLatch(num);
        //每个跑步者一个跑道
        ExecutorService es = Executors.newFixedThreadPool(num);
        //记录比赛成绩
        List<Future<Integer>> futureList = new ArrayList<>();
        //跑步者就位，所有线程处于等待状态
        for(int i = 0;i < num ;i++){
            futureList.add(es.submit(new Runner(begin,end)));
        }
        //发令枪响，跑步者开始跑步
        begin.countDown();
        end.await();
        int count = 0;
        //统计总分
        for(Future<Integer> f:futureList){
            count+=f.get();
        }
        System.out.println("平均分数为："+count/num);
    }

    static class Runner implements Callable<Integer> {

        private CountDownLatch begin;

        private CountDownLatch end;

        public Runner(CountDownLatch begin, CountDownLatch end) {
            this.begin = begin;
            this.end = end;
        }

        @Override
        public Integer call() throws Exception {
            //跑步者的成绩
            int score = new Random().nextInt(25);
            System.out.println("score："+score);
            //等待法令枪响起
            begin.await();
            //跑步中
            TimeUnit.MILLISECONDS.sleep(score);
            //该跑步者跑完全程
            end.countDown();
            return score;
        }
    }
}
